import { AxiosRequestConfig } from '../types/index'
import { isDate, isObject } from './util'

function encode(val: string): string {
  return encodeURIComponent(val)
    .replace(/%40/g, '@')
    .replace(/%3A/gi, ':')
    .replace(/%24/g, '$')
    .replace(/%2C/gi, ',')
    .replace(/%20/g, '+')
    .replace(/%5B/gi, '[')
    .replace(/%5D/gi, ']')
}

export function processRequestParams(config: AxiosRequestConfig): string {
  let { params, url } = config
  // 如果没有传递params选项则return
  if (!params) return url

  const paramKeys = Object.keys(params)
  let processedArr = []

  for (let key of paramKeys) {
    const value = params[key]
    if (value === undefined || value === null) {
      continue
    } else if (isDate(value)) {
      processedArr.push([key, value.toISOString()].join('='))
    } else if (isObject(value)) {
      processedArr.push([key, JSON.stringify(value)].join('='))
    } else {
      processedArr.push([encode(key), encode(value)].join('='))
    }
  }

  if (url.includes('#')) {
    url = url.slice(0, url.indexOf('#'))
  }

  url += (url.includes('?') ? '&' : '?') + processedArr.join('&')

  return url
}
